
package com.eyedog.video.videodetail;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.eyedog.library.utils.DensityUtils;
import com.eyedog.video.R;
import com.eyedog.video.VApplication;
import com.eyedog.video.http.HttpClient;
import com.eyedog.video.http.ICallback;
import com.eyedog.video.mine.ProfileAlertDialog;
import com.eyedog.video.mine.ProfileInstance;
import com.wallj.videolibrary.base.BaseVideoActivity;
import com.wallj.videolibrary.base.VideoPlayerInstance;
import com.wallj.videolibrary.player.GLVideoSurfaceView;
import com.wallj.videolibrary.player.WaterMarkEntity;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.utils.StringUtils;

public class VideoDetailActivity extends BaseVideoActivity
        implements View.OnClickListener, constract.IWaterMarkView {

    private final String TAG = "VideoDetailActivity";

    protected int SCREEN_ORIENTATION = 0;// 0：未更改; 1：更改过;

    private static final int sDefaultTimeout = 3000;

    private GLVideoSurfaceView mSurfaceView;

    private ImageView mPauseButton, mPreVideoButton, mFrontVideoButton, mFullScreen, mShrinkScreen,
            mIvPlay, mIvVolume;

    private SeekBar mProgress;

    private TextView mEndTime, mCurrentTime, mTvTitle;

    private LinearLayout mMediaController;

    private WaterMarkPresenter presenter;

    protected View mControllerLayout, mOperationLayout, mCloseView, mTitleView, mPlayerView;

    private boolean mDragging;

    private boolean mShowing;

    private int mCurrentBufferPercentage;

    private long mDuration;

    protected int mVideoWidth, mVideoHeight;

    private String mVideoUrl;

    private int mScreenWidht, mScreenHeight;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        statusBarColor = Color.BLACK;
        super.onCreate(savedInstanceState);
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        mScreenWidht = metrics.widthPixels;
        mScreenHeight = metrics.heightPixels;
    }

    @Override
    protected void onContentCreated(ViewStub contentLayout) {
        mRootLayout.setPadding(0, 0, 0, 0);
        Intent intent = getIntent();
        Bundle data = intent.getExtras();
        mVideoUrl = data.getString("VIDEO_URL");
        String thumbUrl = data.getString("THUMB_URL");
        String title = data.getString("TITLE");
        contentLayout.setLayoutResource(R.layout.activity_videodetail_ad);
        contentLayout.inflate();
        mRootLayout.setBackgroundColor(Color.parseColor("#272727"));
        mContentLayout.setBackgroundColor(Color.parseColor("#272727"));
        mIvVolume = (ImageView) findViewById(R.id.iv_volume);
        mIvVolume.setOnClickListener(this);
        mControllerLayout = findViewById(R.id.fl_video_root);
        mControllerLayout.setOnTouchListener(controllerTouchListener);
        mControllerLayout.setClickable(true);
        mTitleView = findViewById(R.id.title_view);
        mPlayerView = findViewById(R.id.player_view);
        mPauseButton = (ImageView) findViewById(R.id.app_video_play);
        mPauseButton.setOnClickListener(this);
        mPreVideoButton = (ImageView) findViewById(R.id.iv_play_back);
        mPreVideoButton.setOnClickListener(this);
        mFrontVideoButton = (ImageView) findViewById(R.id.iv_play_front);
        mFrontVideoButton.setOnClickListener(this);
        mOperationLayout = findViewById(R.id.ll_operation_bar);
        mProgress = (SeekBar) findViewById(R.id.app_video_seekBar);
        mProgress.setOnSeekBarChangeListener(mSeekListener);
        mProgress.setMax(1000);
        mIvPlay = (ImageView) findViewById(R.id.iv_play);
        if (mIvPlay != null) {
            mIvPlay.setOnClickListener(this);
            if (VideoPlayerInstance.getInstance().hasPlayerPrepared()) {
                mIvPlay.setVisibility(View.GONE);
                // mControllerLayout.setBackgroundColor(Color.BLACK);
            }
        }
        mCurrentTime = (TextView) findViewById(R.id.app_video_currentTime);
        mEndTime = (TextView) findViewById(R.id.app_video_endTime);
        mMediaController = (LinearLayout) findViewById(R.id.app_media_controller);

        mFullScreen = (ImageView) findViewById(R.id.view_jky_player_fullscreen);
        if (mFullScreen != null) {
            mFullScreen.setOnClickListener(this);
            mMediaController.setVisibility(View.VISIBLE);
        }
        mShrinkScreen = (ImageView) findViewById(R.id.view_jky_player_shrinkscreen);
        if (mShrinkScreen != null) {
            mShrinkScreen.setOnClickListener(this);
        }
        mSurfaceView = (GLVideoSurfaceView) findViewById(R.id.surface_view);
        onSurfaceViewCreated(mSurfaceView);
        mCloseView = findViewById(R.id.close_button);
        mCloseView.setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        if (!TextUtils.isEmpty(title)) {
            mTvTitle.setText(title);
        }
        presenter = new WaterMarkPresenter(this, new WaterMarkModel());
        presenter.displayWaterMark();
        VideoPlayerInstance.getInstance().setPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                postUI(new Runnable() {
                    @Override
                    public void run() {
                        show(sDefaultTimeout);
                    }
                });
            }
        });
    }

    CommonPopupWindow volumeWindow;

    boolean isFromeUser = false;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_play_back: {
                final MediaPlayer mediaPlayer = getMediaPlayer();
                if (mediaPlayer == null) {
                    return;
                }
                int currentProgress = mProgress.getProgress();
                int maxProgress = mProgress.getMax();
                long duration = mediaPlayer.getDuration();
                if (duration > 10 * 1000) {
                    mediaPlayer.pause();
                    int deltaProgress = (int) (maxProgress * 10.0f * 1000 / duration);
                    int backProgress = currentProgress - deltaProgress;
                    backProgress = backProgress >= 0 ? backProgress : 0;
                    isFromeUser = true;
                    mProgress.setProgress(backProgress);
                }
                show(1000);
            }
                break;
            case R.id.iv_play_front: {
                final MediaPlayer mediaPlayer = getMediaPlayer();
                if (mediaPlayer == null) {
                    return;
                }
                int currentProgress = mProgress.getProgress();
                int maxProgress = mProgress.getMax();
                long duration = mediaPlayer.getDuration();
                if (duration > 10 * 1000) {
                    mediaPlayer.pause();
                    int deltaProgress = (int) (maxProgress * 10.0f * 1000 / duration);
                    int frontProgress = currentProgress + deltaProgress;
                    frontProgress = frontProgress <= maxProgress ? frontProgress : maxProgress;
                    isFromeUser = true;
                    mProgress.setProgress(frontProgress);
                }
                show(1000);
            }
                break;
            case R.id.iv_volume: {
                final MediaPlayer mediaPlayer = getMediaPlayer();
                if (mediaPlayer == null) {
                    return;
                }
                if (volumeWindow == null) {
                    volumeWindow = new CommonPopupWindow(this, R.layout.window_volume,
                            DensityUtils.dp2px(this, 40), DensityUtils.dp2px(this, 100)) {
                        @Override
                        protected void initView() {
                            View content = getContentView();
                            SeekBar volumeSeek = (SeekBar) content.findViewById(R.id.volume_bar);
                            volumeSeek.setMax(100);
                            volumeSeek.setOnSeekBarChangeListener(
                                    new SeekBar.OnSeekBarChangeListener() {
                                        @Override
                                        public void onProgressChanged(SeekBar seekBar, int i,
                                                boolean b) {
                                            if (mediaPlayer != null) {
                                                VideoPlayerInstance.getInstance()
                                                        .setCurrentVolume(i);
                                            }
                                        }

                                        @Override
                                        public void onStartTrackingTouch(SeekBar seekBar) {
                                        }

                                        @Override
                                        public void onStopTrackingTouch(SeekBar seekBar) {
                                            volumeWindow.getPopupWindow().dismiss();
                                        }
                                    });
                        }

                        @Override
                        protected void initEvent() {
                        }
                    };
                }
                if (mediaPlayer != null) {
                    int volume = VideoPlayerInstance.getInstance().getCurrentVolume();
                    volumeWindow.setProgress(volume);
                }
                volumeWindow.showBashOfAnchor(mIvVolume, new LayoutGravity(LayoutGravity.TO_ABOVE),
                        0, -1 * DensityUtils.dp2px(this, 100));
            }
                break;
            case R.id.close_button:
                finish();
                break;
            case R.id.app_video_play:
                MediaPlayer player = getMediaPlayer();
                if (player != null && hasPlayerPrepared()) {
                    if (player.isPlaying()) {
                        player.pause();
                    } else {
                        player.start();
                    }
                }
                show(1000);
                break;
            case R.id.view_jky_player_fullscreen:
                if (getMediaPlayer() != null && hasPlayerPrepared()) {
                    int width = mSurfaceView.getMeasuredWidth();
                    int height = mSurfaceView.getMeasuredHeight();
                    if (width > 0 && height > 0) {
                        int parentWidth = mRootLayout.getMeasuredWidth();
                        int parentHeight = mRootLayout.getMeasuredHeight();
                        if (1.0f * width / height > 1.0f * parentWidth / parentHeight) {
                            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        }
                    }
                    onFullScreen();
                }
                break;
            case R.id.view_jky_player_shrinkscreen:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                onShrinkFullScreen();
                break;
            case R.id.iv_play: {
                final int watchTimes = ProfileInstance.getInstance()
                        .getProfileEntity().times_watched;
                if (watchTimes > 0) {
                    if (!TextUtils.isEmpty(mVideoUrl)) {
                        // mControllerLayout.setBackgroundColor(Color.BLACK);
                        view.setVisibility(View.GONE);
                        HttpClient.getInstance().requestDeductVideo(
                                ProfileInstance.getInstance().getUniqueCode(),
                                new ICallback<Integer>() {
                                    @Override
                                    public void onLoadSuccess(Integer aBoolean) {
                                        ProfileInstance.getInstance().getProfileEntity()
                                                .setTimes_watched(watchTimes - 1);
                                    }

                                    @Override
                                    public void onLoadFailed(String err) {
                                    }
                                });

                        startPlay(VApplication.getAppContext(), mVideoUrl);
                    }
                } else {
                    ProfileAlertDialog profileAlertDialog = new ProfileAlertDialog(this);
                    profileAlertDialog.show();
                }
            }
                break;
        }
    }

    protected void onFullScreen() {

    }

    protected void onShrinkFullScreen() {

    }

    private void updatePausePlay() {
        MediaPlayer mMediaPlayer = getMediaPlayer();
        if (mPauseButton == null || mMediaPlayer == null) {
            return;
        }
        if (mMediaPlayer.isPlaying()) {
            mPauseButton.setImageResource(R.drawable.ic_pause);
        } else {
            mPauseButton.setImageResource(R.drawable.ic_play);
        }
    }

    private long setProgress() {
        MediaPlayer mMediaPlayer = getMediaPlayer();
        if (mMediaPlayer == null || mDragging) {
            return 0;
        }
        long position = mMediaPlayer.getCurrentPosition();
        long duration = mMediaPlayer.getDuration();
        if (mProgress != null) {
            if (duration > 0) {
                long pos = 1000L * position / duration;
                mProgress.setProgress((int) pos);
            }
            int percent = mCurrentBufferPercentage;
            mProgress.setSecondaryProgress(percent * 10);
        }
        mDuration = duration;
        if (mEndTime != null) {
            mEndTime.setText(StringUtils.generateTime(mDuration));
        }
        if (mCurrentTime != null) {
            mCurrentTime.setText(StringUtils.generateTime(position));
        }

        return position;
    }

    @Override
    public void showWaterMark(WaterMarkEntity waterMarkEntity) {
        mSurfaceView.showWaterMark(waterMarkEntity);
    }

    public void show(int timeout) {
        if (!mShowing) {
            if (mPauseButton != null) {
                mPauseButton.requestFocus();
            }
            mMediaController.setVisibility(View.VISIBLE);
            mShowing = true;
        }
        removeUIMessage(SHOW_PROGRESS);
        sendEmptyUIMessage(SHOW_PROGRESS);
        if (timeout != 0) {
            removeUIMessage(FADE_OUT);
            sendUIMessageDelay(obtainUIMessage(FADE_OUT), timeout);
        }
        mOperationLayout.setVisibility(View.VISIBLE);
        updatePausePlay();
    }

    public void hide() {
        if (mShowing && mShrinkScreen != null) {
            mMediaController.setVisibility(View.GONE);
            mShowing = false;
        }
        mOperationLayout.setVisibility(View.GONE);
    }

    private static final int FADE_OUT = 1;

    private static final int SHOW_PROGRESS = 2;

    @Override
    protected void handleUIMessage(Message msg) {
        super.handleUIMessage(msg);
        long pos;
        switch (msg.what) {
            case FADE_OUT:
                hide();
                break;
            case SHOW_PROGRESS:
                pos = setProgress();
                Log.i(TAG, "mDragging:" + mDragging + ";mShowing:" + mShowing + ";pos:" + pos);
                if (!mDragging && mShowing) {
                    msg = obtainUIMessage(SHOW_PROGRESS);
                    sendUIMessageDelay(msg, 1000 - (pos % 1000));
                    updatePausePlay();
                }
                break;
        }
    }

    private SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
        public void onStartTrackingTouch(SeekBar bar) {
            mDragging = true;
            MediaPlayer player = getMediaPlayer();
            if (player != null) {
                show(3600000);
                player.pause();
                removeUIMessage(SHOW_PROGRESS);
            }
        }

        public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
            if (!fromuser && !isFromeUser) {
                return;
            }

            long newposition = (mDuration * progress) / 1000;
            if (!fromuser && isFromeUser) {
                isFromeUser = false;
                MediaPlayer mPlayer = getMediaPlayer();
                if (mPlayer != null) {
                    show(sDefaultTimeout);
                    mPlayer.seekTo(newposition);
                    mPlayer.start();
                    sendEmptyUIMessageDelay(SHOW_PROGRESS, 1000);
                }
                removeUIMessage(SHOW_PROGRESS);
                mDragging = false;
            }
            String time = StringUtils.generateTime(newposition);
            if (mCurrentTime != null) {
                mCurrentTime.setText(time);
            }
        }

        public void onStopTrackingTouch(SeekBar bar) {
            MediaPlayer mPlayer = getMediaPlayer();
            if (mPlayer != null) {
                show(sDefaultTimeout);
                mPlayer.seekTo((mDuration * bar.getProgress()) / 1000);
                mPlayer.start();
                sendEmptyUIMessageDelay(SHOW_PROGRESS, 1000);
            }
            removeUIMessage(SHOW_PROGRESS);
            mDragging = false;
        }
    };

    View.OnTouchListener controllerTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            MediaPlayer player = getMediaPlayer();
            Log.i(TAG, "onTouchview " + mShowing + hasPlayerPrepared());
            if (player != null && hasPlayerPrepared()) {
                show(sDefaultTimeout);
            }
            return false;
        }
    };

    @Override
    public void onBackPressed() {
        if (mShrinkScreen != null) {
            mShrinkScreen.performClick();
        } else {
            super.onBackPressed();
        }
    }
}
